package com.cbb.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.cbb.bean.UserBean;
import com.cbb.bean.UserData;
import com.cbb.net.HttpLoad;
import com.android.volley.toolbox.NetworkImageView;
import com.cbb.admin.cbb.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by jxk on 2018/3/18.
 * Email:676585325@qq.com
 */
public class Utils {

    public static Dialog dialog = null;
    /**
     * 手机网络检测
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return true;
            }
        }
        ToastUtils.show(context, "请检查您的网络连接！");
        return false;
    }

    /**
     * 获取不同尺寸的默认图片
     *
     * @param resId 资源ID
     * @return
     */
    public static int getDefaultImage(int resId) {
        if (resId == -1) {
            return R.mipmap.icon_default_image;
        } else {
            return resId;
        }
    }

    /**
     * 保存用户信息
     */
    public static void saveUserInfo(Context context, UserData userBean) {
        SharedPreUtils.putString(context, SharedPre.User.TOKEN_ID, userBean.tokenid);
      //  UserBean userBean = data.userinfo;
       /* SharedPreUtils.putString(context,SharedPre.User.TOKEN_ID, userBean.tokenId);
        SharedPreUtils.putInt(context,SharedPre.User.ID, userBean.id);
        SharedPreUtils.putString(context,SharedPre.User.TOKEN, userBean.token);
        SharedPreUtils.putString(context, SharedPre.User.MOBILE, userBean.mobile);
        SharedPreUtils.putString(context, SharedPre.User.NAME, userBean.realname);
        SharedPreUtils.putString(context, SharedPre.User.PASSWORD, userBean.password);
        SharedPreUtils.putString(context, SharedPre.User.WX_ACCOUNT, userBean.wxAccount);
        SharedPreUtils.putString(context, SharedPre.User.WX_OPENID, userBean.wxOpenid);
        SharedPreUtils.putString(context, SharedPre.User.ID_CARD, userBean.idCard);
        SharedPreUtils.putString(context, SharedPre.User.CITY, userBean.city);
        SharedPreUtils.putString(context, SharedPre.User.ID_PHOTO_URL, userBean.idPhotoUrl);
        SharedPreUtils.putString(context, SharedPre.User.INTERAL, userBean.integral);
        SharedPreUtils.putString(context, SharedPre.User.INVITE_CODE, userBean.inviteCode);
        SharedPreUtils.putString(context, SharedPre.User.SEX, userBean.sex);
        SharedPreUtils.putString(context, SharedPre.User.EMAIL, userBean.email);
        SharedPreUtils.putString(context, SharedPre.User.BIRTHDAY, userBean.birthday);
        SharedPreUtils.putString(context, SharedPre.User.CREAT_TIME, userBean.createTime);
        SharedPreUtils.putString(context, SharedPre.User.UPDATE_TIME, userBean.updateTime);
        SharedPreUtils.putString(context, SharedPre.User.IS_ENABLE, userBean.isEnabled);
        SharedPreUtils.putString(context, SharedPre.User.IS_DELETED, userBean.isDeleted);*/
    }

    /**
     * 获取用户信息
     */
    public static UserBean getUserInfo(Context context) {
   /*     if (!isLoginUser(context)) {
            return null;
        }*/
        UserBean userBean = new UserBean();
        userBean.tokenId = SharedPreUtils.getString(context, SharedPre.User.TOKEN_ID);
       /* UserBean userBean = new UserBean();
        userBean.tokenId = SharedPreUtils.getString(context, SharedPre.User.TOKEN_ID);
        userBean.id = SharedPreUtils.getInt(context, SharedPre.User.ID, 0);
        userBean.token = SharedPreUtils.getString(context, SharedPre.User.TOKEN);
        userBean.realname = SharedPreUtils.getString(context, SharedPre.User.NAME);
        userBean.mobile = SharedPreUtils.getString(context, SharedPre.User.MOBILE);
        userBean.password = SharedPreUtils.getString(context, SharedPre.User.PASSWORD);
        userBean.wxAccount = SharedPreUtils.getString(context, SharedPre.User.WX_ACCOUNT);
        userBean.wxOpenid = SharedPreUtils.getString(context, SharedPre.User.WX_OPENID);
        userBean.idCard = SharedPreUtils.getString(context, SharedPre.User.ID_CARD);
        userBean.city = SharedPreUtils.getString(context, SharedPre.User.CITY);
        userBean.integral = SharedPreUtils.getString(context, SharedPre.User.INTERAL);
        userBean.inviteCode = SharedPreUtils.getString(context, SharedPre.User.INVITE_CODE);
        userBean.idPhotoUrl = SharedPreUtils.getString(context, SharedPre.User.ID_PHOTO_URL);
        userBean.sex = SharedPreUtils.getString(context, SharedPre.User.SEX);
        userBean.email = SharedPreUtils.getString(context, SharedPre.User.EMAIL);
        userBean.education = SharedPreUtils.getString(context, SharedPre.User.EDUCATION);
        userBean.createTime = SharedPreUtils.getString(context, SharedPre.User.CREAT_TIME);
        userBean.updateTime = SharedPreUtils.getString(context, SharedPre.User.UPDATE_TIME);
        userBean.isEnabled = SharedPreUtils.getString(context, SharedPre.User.IS_ENABLE);
        userBean.isDeleted = SharedPreUtils.getString(context, SharedPre.User.IS_DELETED);*/
        return userBean;
    }

    public static String getTokenId(Context context) {
        return SharedPreUtils.getString(context, SharedPre.User.TOKEN_ID);
    }

    //清除SP中用户的信息
    public static void cleanUserInfo(Context context) {
        SharedPreUtils.removeSharedKey(context, SharedPre.User.TOKEN_ID);
      /*  SharedPreUtils.removeSharedKey(context, SharedPre.User.ID);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.TOKEN);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.NAME);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.MOBILE);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.PASSWORD);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.MOBILE);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.PASSWORD);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.WX_ACCOUNT);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.WX_OPENID);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.ID_CARD);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.CITY);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.INVITE_CODE);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.INTERAL);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.ID_PHOTO_URL);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.SEX);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.EMAIL);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.EDUCATION);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.CREAT_TIME);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.UPDATE_TIME);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.IS_DELETED);
        SharedPreUtils.removeSharedKey(context, SharedPre.User.IS_DELETED);*/
    }

    public static int dipDimensionInteger(Context context, float value) {
        return (int) (dipDimensionFloat(context, value) + 0.5f);
    }

    public static float dipDimensionFloat(Context context, float value) {
        return context == null ? value : TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, value, context.getResources()
                        .getDisplayMetrics());
    }


    /**
     * 获得屏幕宽度
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 是否为登录用户
     * 注意：正常情况下是后去token，现在后台没有写，暂时以用户ID代替。
     */
  /*  public static boolean isLoginUser(Context context) {
        // return (!TextUtils.isEmpty(SharedPreUtils.getString(context, SharedPre.App.ACCESS_TOKEN)));
        return (Utils.getUserID(context) != 0);
    }*/

  /*  *//**
     * 获取userID
     *//*
    public static int getUserID(Context context) {
        return SharedPreUtils.getInt(context, SharedPre.User.ID, 0);
    }

    public static String getUserPhone(Context context) {
        return SharedPreUtils.getString(context, SharedPre.User.MOBILE);
    }
    public static String getUserToken(Context context) {
        return SharedPreUtils.getString(context, SharedPre.User.TOKEN);
    }
    public static String getTokenId(Context context) {
        return SharedPreUtils.getString(context, SharedPre.User.TOKEN_ID);
    }
    *//**
     * 获取username
     *//*
    public static String getUserName(Context context) {
        return SharedPreUtils.getString(context, SharedPre.User.NAME);
    }

    *//**
     * 保存购物车商品数量
     *//*
    public static void saveCartNo(Context context, int number) {
        SharedPreUtils.putInt(context, SharedPre.Cart.NUMBER, number);
    }

    *//**
     * 获取购物车商品数量
     *//*
    public static int getCartNo(Context context) {
        return SharedPreUtils.getInt(context, SharedPre.Cart.NUMBER, 0);
    }
*/
    /**
     * 格式化购物车中的价格
     */
    public static String PriceFormat(String price) {
        if (TextUtils.isEmpty(price)) {
            return "0.00";
        }
        DecimalFormat df = new DecimalFormat("#0.00");
        try {
            return df.format(Double.valueOf(price));
        } catch (Exception e) {
            return "0.00";
        }
    }

    // 判断手机号码的正确性
    public static boolean isPhoneNumber(String mobiles) {
        String phoneStyle = "^1[345678]\\d{9}$";
        Pattern p = Pattern.compile(phoneStyle);
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 验证邮箱格式
     */
    public static boolean isEmail(String strEmail) {
        String strPattern = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strEmail);
        return m.matches();
    }

    /**
     * 设置加载网络图片 宽度和屏幕宽度一样，高度按比例自适应
     */
    public static void setImageViewAdaptive(Context context, NetworkImageView imageView, String imageUrl) {
        LayoutParams params = (LayoutParams) imageView.getLayoutParams();

        imageView.setAdjustViewBounds(true);
        imageView.setScaleType(ScaleType.FIT_XY);
        params.width = Utils.getScreenWidth(context);
        params.height = LayoutParams.WRAP_CONTENT;
        imageView.setLayoutParams(params);

        imageView.setMaxWidth(Utils.getScreenWidth(context));
        imageView.setMaxHeight(Utils.getScreenWidth(context) * 5);

        HttpLoad.getImage(context, imageUrl, -1, imageView);
    }
    /**
     * 设置加载网络图片 宽度为2/3屏幕  高度自适应
     */
    public static void setAdaptHeightImg(Context context, NetworkImageView imageView, String imageUrl) {
        LayoutParams params = (LayoutParams) imageView.getLayoutParams();

        imageView.setAdjustViewBounds(true);
        imageView.setScaleType(ScaleType.CENTER_CROP);
        params.width = Utils.getScreenWidth(context) * 2/3;
        params.height = LayoutParams.WRAP_CONTENT;
        imageView.setLayoutParams(params);

        imageView.setMaxWidth(Utils.getScreenWidth(context));
        imageView.setMaxHeight(Utils.getScreenWidth(context) * 5);

        HttpLoad.getImage(context, imageUrl, -1, imageView);
    }


    public static String getImageBase64(ImageView imageView) {
        // decode to bitmap
        imageView.buildDrawingCache();
        Bitmap bitmap = imageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();

        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 获取系统时间
     */
    public static String getSystemTime() {
        SimpleDateFormat dateFormat24 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat24.format(Calendar.getInstance().getTime());
    }

    //压缩200k以下的大小上传
    public static String getImagecacheBase64(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 100是压缩率不压缩，如果是30就是压缩70%，压缩后的存放在baos中
        if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();// 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap1 = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 1920f;// 这里设置高度为800f   1280
        float ww = 1080f;// 这里设置宽度为480f    720
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap1 = BitmapFactory.decodeStream(isBm, null, newOpts);
        baos.reset();// 重置baos即清空baos
        bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > 220) { // 循环判断如果压缩后图片是否大于200kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            options -= 10;// 每次都减少10
            bitmap1.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
        }
        byte[] bytes = baos.toByteArray();
        try {
            baos.flush();
            baos.close();
            // bitmap.recycle();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Base64.encodeToString(bytes, Base64.DEFAULT);

    }
    /**
     * 是否为新版本
     *
     * @param context
     * @return
     */
    public static boolean isNewVersion(Context context, int versionCodeNew) {
        boolean flag = false;
        //int versionCodeOld = SharedPreUtils.getInt(context, SharedPre.App.VERSION, 1);
        try {
            int versionCodeOld = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS).versionCode;
            flag = versionCodeNew > versionCodeOld;
        /*    if (flag) {
                SharedPreUtils.putInt(context, SharedPre.App.VERSION, versionCodeNew);
                SharedPreUtils.putString(context, SharedPre.App.APP_VERSION_NAME,
                        context.getPackageManager().getPackageInfo(context.getPackageName(),
                                PackageManager.GET_CONFIGURATIONS).versionName);
            }*/
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return flag;
    }



    public static String convertUnicode(String ori) {
        char aChar;
        int len = ori.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = ori.charAt(x++);
            if (aChar == '\\') {
                aChar = ori.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = ori.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }
            } else
                outBuffer.append(aChar);

        }
        return outBuffer.toString();
    }

    /**
     *
     * @param jsonStr
     * @return
     */
    public static String format(String jsonStr) {
        int level = 0;
        StringBuffer jsonForMatStr = new StringBuffer();
        for(int i=0;i<jsonStr.length();i++){
            char c = jsonStr.charAt(i);
            if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
                jsonForMatStr.append(getLevelStr(level));
            }
            switch (c) {
                case '{':
                case '[':
                    jsonForMatStr.append(c+"\n");
                    level++;
                    break;
                case ',':
                    jsonForMatStr.append(c+"\n");
                    break;
                case '}':
                case ']':
                    jsonForMatStr.append("\n");
                    level--;
                    jsonForMatStr.append(getLevelStr(level));
                    jsonForMatStr.append(c);
                    break;
                default:
                    jsonForMatStr.append(c);
                    break;
            }
        }

        return jsonForMatStr.toString();

    }
    private static String getLevelStr(int level){
        StringBuffer levelStr = new StringBuffer();
        for(int levelI = 0;levelI<level ; levelI++){
            levelStr.append("\t");
        }
        return levelStr.toString();
    }
    /**
     * 根据url获取图片宽高
     */

    public static Bitmap getBitMBitmap(String urlpath) {
        Bitmap map = null;
        try {
            URL url = new URL(urlpath);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            map = BitmapFactory.decodeStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
    /*public static BufferedImage getBufferedImage(String imgUrl) {
        URL url = null;
        InputStream is = null;
        BufferedImage img = null;
        try {
            url = new URL(imgUrl);
            is = url.openStream();
            img = ImageIO.read(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return img;
    }*/
        public static void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                return;
            }
            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
            LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
        }
    /**
     * 弹出的打电话dialog
     */
    public static void popup(final Context context, final String phone){

      /*  AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
        View v2 = LayoutInflater.from(context).inflate(R.layout.alert_receive_product, null);
        TextView title1 = (TextView) v2.findViewById(R.id.tv_alert_receive_title);
        TextView content1 = (TextView) v2.findViewById(R.id.tv_alert_receive_content);
        Button btnCancel1 = (Button) v2.findViewById(R.id.alert_receive_qx);
        Button btnSubmit1 = (Button) v2.findViewById(R.id.alert_receive_qd);
        title1.setText("拨打电话");
        content1.setText(phone);
        btnCancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btnSubmit1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                //用intent启动拨打电话
                Intent intent1 = new Intent("android.intent.action.CALL", Uri.parse("tel:"+ phone));
                context.startActivity(intent1);
            }
        });
        builder1.setView(v2);
        builder1.create();
        dialog = builder1.show();*/
    }
    /**
     * 格式化时间戳
     */
    public static String formateDate(long m){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return  sdf.format(m);
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
    /**
     * 阿拉伯数字转汉字
     * @param string
     * @return
     */
    public static String toChinese(String string){
        String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };
        String result = "";
        int n = string.length();
        for (int i = 0; i < n; i++) {

            int num = string.charAt(i) - '0';

            if (i != n - 1 && num != 0) {
                result += s1[num] + s2[n - 2 - i];
            } else {
                result += s1[num];
            }
        }
        return result;
    }
}
